package com.zyk.scaffold.oauth.keypool.repository;

import com.zyk.scaffold.common.utils.AssertUtil;
import com.zyk.scaffold.common.utils.BeanCopyUtil;
import com.zyk.scaffold.oauth.keypool.pojo.dto.KeyInfoDTO;
import com.zyk.scaffold.oauth.keypool.pojo.entry.KeyInfo;
import com.zyk.scaffold.oauth.keypool.store.KeyPoolStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.*;


/**
 * 对秘钥存储库查询封装
 */
@Repository
public class KeyPoolRepository {
    @Autowired
    private KeyPoolStore keyPoolStore;

    public List<KeyInfoDTO> getRandomKeys(int nums) {
        AssertUtil.isFalse(nums > keyPoolStore.getMaxNum(), "数量不能超过：" + keyPoolStore.getMaxNum());
        if(nums == keyPoolStore.getMaxNum()){
            return BeanCopyUtil.copyListProperties(keyPoolStore.selectKeyInfo(null), KeyInfoDTO::new);
        }
        Set<Integer> randomIdSets = new HashSet<>();
        Random random = new Random();
        while (randomIdSets.size() < nums){
            randomIdSets.add(random.nextInt(keyPoolStore.getMaxNum() - 1));
        }
        List<Integer> randomIds = new ArrayList<>(randomIdSets);
        List<KeyInfo> keyInfos = keyPoolStore.selectKeyInfo(randomIds);
        return BeanCopyUtil.copyListProperties(keyInfos, KeyInfoDTO::new);
    }

    public List<KeyInfoDTO> selectKeyInfo(List<Integer> ids) {
        List<KeyInfo> keyInfos = keyPoolStore.selectKeyInfo(ids);
        return BeanCopyUtil.copyListProperties(keyInfos, KeyInfoDTO::new);
    }
}
